package com.rz.admin.interceptor;

import com.rz.core.exception.GlobalException;
import com.rz.core.kit.HashKit;
import com.rz.core.kit.RedisKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Resource
    private RedisKit redisKit;
    private Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userKey = request.getHeader("userKey");
        if(userKey.equals("1")){
            return true;
        }

        String sign = request.getHeader("sign");
        String time = request.getHeader("time");

        logger.info("请求参数 sign={},time={},userKey={}",sign,time,userKey);

        if(StringUtils.isEmpty(sign)){
            throw new GlobalException(10011,"缺少签名参数【sign】，请重新登录再试");
        }
        if(StringUtils.isEmpty(userKey)){
            throw new GlobalException(10012,"缺少用户Key【userKey】，请重新登录再试");
        }
        if(StringUtils.isEmpty(time)){
            throw new GlobalException(10013,"缺少请求时间【time】，请重新登录再试");
        }

        Object tokenObj = redisKit.getValue("userkey_"+userKey);
        if (tokenObj == null) {
            throw new GlobalException(10010,"未找到用户对应的令牌token，请重新登录再试");
        }
        String token = tokenObj.toString();
        String[] tokenKeys = token.split("_");
        String realSign = HashKit.sha1(tokenKeys[0] + time + tokenKeys[1]);
        logger.info("计算后的sign = {}",realSign);
        boolean isok = realSign.equals(sign);
        if(!isok){
            throw new GlobalException(10014,"【sign】签名参数不一致，请重试");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
